# numLst2idx.py
from constants import NATURE_TO_PROJECT_GUA_IDX
from utils.format_lst import is_format, format_max3_to_max2


class GuaConverter:
    def __init__(self, num_lst: list[int]):
        self.num_lst: list[int] = num_lst

    @staticmethod
    def to_nature_idx_max2(num_lst):
        idx = 0
        for i in range(len(num_lst)):
            n = num_lst[i]
            idx += (n - 1) * 2 ** i
        return idx

    @classmethod
    def to_gua_idx_max2(cls, num_lst):
        return NATURE_TO_PROJECT_GUA_IDX[cls.to_nature_idx_max2(num_lst)]
    @classmethod
    def to_nature_idx_max3(cls,num_lst):
        '''`num_lst` 范围在0-3，长度不限'''
        return [cls(li).get_nature_idx() for li in format_max3_to_max2(num_lst)]
    def get_nature_idx(self) -> int | list[int]:
        """
        已知 numLst 求序数
        :return: 卦的自然序号
        """
        if is_format(self.num_lst, 'Max2'):
            return self.to_nature_idx_max2(self.num_lst)
        elif is_format(self.num_lst, 'Max3'):
            # return [GuaConverter(li).get_nature_idx() for li in format_max3_to_max2(self.num_lst)]
            return self.to_nature_idx_max3(self.num_lst)
        else:
            print('numLst s Format must between 0-3 or 1-2,while your numLst:', self.num_lst)

    def get_gua_idx(self, is_pair: bool = False) -> int | list[int]:
        """
        numLst to gua idx(-which project is using)
        :return: 卦的项目序号
        """
        if is_format(self.num_lst, 'Max2', 6):
            # gua_idx = NATURE_TO_PROJECT_GUA_IDX[self.get_nature_idx()]
            gua_idx = self.to_gua_idx_max2(self.num_lst)
            if is_pair:
                return gua_idx, gua_idx
            else:
                return gua_idx
        elif is_format(self.num_lst, 'Max3', 6):
            return [GuaConverter(li).get_gua_idx() for li in format_max3_to_max2(self.num_lst)]
        else:
            print('numLst s Format must between 0-3 or 1-2 and len==6,while your numLst:', self.num_lst)

    def get_home_idx(self) -> int:
        """
        获取本宫卦的序号
        :return: 本宫卦的序号
        """
        res = self.get_gua_idx()
        gua_idx = res[0] if isinstance(res, list) else res
        home_gua = gua_idx // 8 * 8
        return home_gua


if __name__ == '__main__':
    max2 = [1, 1, 2, 1, 2, 2]
    max3 = [0, 3, 2, 1, 2, 0]
    numLsts = [
        max3,  # max3 返回一个列表两个数
        max2]  # max2 返回一个数
    for numLst in numLsts:
        print(GuaConverter(numLst).get_gua_idx())
        print(GuaConverter(numLst).get_nature_idx())
        print(GuaConverter(numLst).get_home_idx())

    # 2. max2 to gua idx
    print(max2, GuaConverter.to_gua_idx_max2(max2))
    print(max2, GuaConverter.to_gua_idx_max2([1, 1, 1, 1, 2, 2]))  # 天风姤1 天山遁2
